package com.example.ad.sdk.domain.utils

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import com.example.ad.sdk.domain.helper.ContextHelper
import java.util.UUID
import android.provider.Settings
import android.webkit.WebView
import androidx.annotation.RequiresApi
import androidx.core.content.edit
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.net.Inet4Address
import java.net.Inet6Address
import java.net.NetworkInterface
import java.net.URL
import java.util.TimeZone

/**
 * app/手机设备相关信息
 */
object AppDeviceUtil {
    /**
     * 获取系统的版本信息
     */
    fun systemVersion(): String {
        return Build.VERSION.RELEASE
    }

    /**
     * 获取设备的制造商信息
     */
    fun deviceBrand(): String{
        return Build.BRAND
    }

    /**
     * 获取设备的型号信息
     */
    fun systemModel(): String{
        return Build.MODEL
    }

    /**
     * 获取当前网络类型
     */
    @RequiresApi(Build.VERSION_CODES.M)
    fun networkType(): String{
        val connectivityManager = ContextHelper.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val network = connectivityManager.activeNetwork ?: return "No Internet"
        val networkCapabilities = connectivityManager.getNetworkCapabilities(network) ?: return "Unknown"
        // 根据网络能力判断网络类型
        return when {
            networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) -> {
                //网络使用wi-fi
                if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) "Wi-Fi"
                //网络使用手机网络（数据网络）
                else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) "Cellular"
                //网络使用以太网上网
                else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) "Ethernet"
                //网络使用蓝牙上网
                else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH)) "Bluetooth"
                //网络使用VPN上网
                else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) "VPN"
                //网络使用Wi-Fi感知传输
                else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI_AWARE)) "wifi-Aware"
                //网络使用LoWPAN传输
                else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_LOWPAN)) "LowPAN"
                // 网络使用USB传输
                else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_USB)) "USB"
                else "Unknown"
            }
            else -> "No Internet"
        }
    }

    private val PREFS_FILE = "device_id"
    private val PREFS_DEVICE_ID = "device_id"
    @SuppressLint("HardwareIds")
    fun getUniqueDeviceId(): String {
        val prefs = ContextHelper.context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)
        var deviceId = prefs.getString(PREFS_DEVICE_ID, null)
        if (deviceId == null) {
            // 优先使用Android ID
            deviceId = Settings.Secure.getString(ContextHelper.context.contentResolver, Settings.Secure.ANDROID_ID)
            // 如果Android ID无效，生成UUID
            if (deviceId.isNullOrEmpty() || deviceId == "9774d56d682e549c") {
                deviceId = getUUID()
            }
            // 保存到SharedPreferences
            prefs.edit { putString(PREFS_DEVICE_ID, deviceId) }
        }

        return deviceId
    }

    fun getUUID(): String {
        return getUUID(true)
    }

    fun getUUID(replace: Boolean): String {
        return if (replace) UUID.randomUUID().toString().replace("-", "") else UUID.randomUUID()
            .toString()
    }

    fun systemTimestamp(): Long {
        return System.currentTimeMillis()
    }


    // 获取OAID (需要MSA SDK)
    fun getOAID(context: Context, callback: (String?) -> Unit) {
//        try {
//            MdidSdkHelper.InitSdk(context, true, object : IIdentifierListener {
//                override fun OnSupport(isSupport: Boolean, supplier: IdSupplier?) {
//                    if (isSupport && supplier != null) {
//                        callback(supplier.oaid)
//                    } else {
//                        callback(null)
//                    }
//                }
//            })
//        } catch (e: Exception) {
//            callback(null)
//        }
        //TODO 需要去移动安全联盟官网申请sdk
        callback("")
    }

    // 获取GAID (需要Google Play Services)
    suspend fun getGAID(context: Context): String? = withContext(Dispatchers.IO) {
        try {
            val adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context)
            if (!adInfo.isLimitAdTrackingEnabled) {
                adInfo.id
            } else null
        } catch (e: Exception) {
            null
        }
    }

    // 获取时区
    fun getTimeZone(): String {
        return TimeZone.getDefault().id
    }

    // 获取国家代码
    fun getCountry(context: Context): String {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            context.resources.configuration.locales[0].country
        } else {
            @Suppress("DEPRECATION")
            context.resources.configuration.locale.country
        }
    }

    // 获取User Agent
    fun getUserAgent(context: Context): String {
        return try {
            WebView(context).settings.userAgentString
        } catch (e: Exception) {
            "Android/${Build.VERSION.RELEASE}"
        }
    }

    // 获取IPv4地址
    suspend fun getIPv4(): String? = withContext(Dispatchers.IO) {
        try {
            val url = URL("https://api.ipify.org")
            url.readText().trim()
        } catch (e: Exception) {
            getLocalIPv4()
        }
    }

    // 获取IPv6地址
    suspend fun getIPv6(): String? = withContext(Dispatchers.IO) {
        try {
            val url = URL("https://api6.ipify.org")
            url.readText().trim()
        } catch (e: Exception) {
            getLocalIPv6()
        }
    }

    // 获取本地IPv4
    private fun getLocalIPv4(): String? {
        try {
            val interfaces = NetworkInterface.getNetworkInterfaces()
            while (interfaces.hasMoreElements()) {
                val networkInterface = interfaces.nextElement()
                val addresses = networkInterface.inetAddresses
                while (addresses.hasMoreElements()) {
                    val address = addresses.nextElement()
                    if (!address.isLoopbackAddress && address is Inet4Address) {
                        return address.hostAddress
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    // 获取本地IPv6
    private fun getLocalIPv6(): String? {
        try {
            val interfaces = NetworkInterface.getNetworkInterfaces()
            while (interfaces.hasMoreElements()) {
                val networkInterface = interfaces.nextElement()
                val addresses = networkInterface.inetAddresses
                val address = addresses.nextElement()
                if (!address.isLoopbackAddress && address is Inet6Address) {
                    return address.hostAddress
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    // 获取本地IP地址 (API 21+)
    fun getLocalIPs(): Pair<String?, String?> {
        var ipv4: String? = null
        var ipv6: String? = null

        try {
            val connectivityManager = ContextHelper.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val network = connectivityManager.activeNetwork
                val networkCapabilities = connectivityManager.getNetworkCapabilities(network)

                if (networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true) {
                    NetworkInterface.getNetworkInterfaces().asSequence().forEach { networkInterface ->
                        if (networkInterface.isUp && !networkInterface.isLoopback) {
                            networkInterface.inetAddresses.asSequence().forEach { address ->
                                if (!address.isLoopbackAddress) {
                                    when (address) {
                                        is Inet4Address -> if (ipv4 == null) ipv4 = address.hostAddress
                                        is Inet6Address -> if (ipv6 == null) ipv6 = address.hostAddress
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                // API 21-22 fallback
                NetworkInterface.getNetworkInterfaces().asSequence().forEach { networkInterface ->
                    networkInterface.inetAddresses.asSequence().forEach { address ->
                        if (!address.isLoopbackAddress) {
                            when (address) {
                                is Inet4Address -> if (ipv4 == null) ipv4 = address.hostAddress
                                is Inet6Address -> if (ipv6 == null) ipv6 = address.hostAddress
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return Pair(ipv4, ipv6)
    }

}